<template>
  <div class="addSpare">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="back" @click="goBack">←返回</div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <div class="table">
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="备件名称" prop="partName">
                <el-input
                  v-model="ruleForm.partName"
                  placeholder="请输入备件名称"
                  clearable
                  maxlength="32"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备件编号" prop="partNum">
                <el-input
                  v-model="ruleForm.partNum"
                  placeholder="请输入备件编号"
                  clearable
                  maxlength="32"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="所属备件库" prop="storehouseId">
                <el-cascader
                  v-model="ruleForm.storehouseId"
                  ref="storehouseRef"
                  :props="props"
                  :options="storehouse"
                  clearable
                  placeholder="请选择所属备件库"
                  @change="storehouseChange"
                  style="width: 100%"
                  filterable
                  :show-all-levels="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备件类型" prop="partType">
                <el-cascader
                  v-model="ruleForm.partType"
                  ref="paetTypeRef"
                  :props="props"
                  :options="partTypes"
                  clearable
                  :show-all-levels="false"
                  placeholder="请选择备件类型"
                  @change="partTypeChange"
                  style="width: 75%"
                  filterable
                />
                <el-button
                  type="primary"
                  plain
                  style="width: 25%"
                  @click="addPartType()"
                  >添加类型</el-button
                >
                <div class="tips">
                  备件类型，可在【企业设置管理-数据字典】中配置管理
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div style="width: 100%">
          <el-form-item
            label="批次设置"
            :rules="{ required: true }"
            style="width: 100%"
          >
            <div class="tips" style="line-height: 32px">
              提示：实际库存将自动获取批次设置中的库存显示数量，多个批次数量累加计算
            </div>
            <el-form-item
              v-for="(item, index) in ruleForm.partBatchList"
              style="width: 100%; margin-bottom: 15px"
            >
              <el-row style="width: 100%">
                <el-col :span="5">
                  <el-form-item
                    :prop="`partBatchList[${index}].batchNum`"
                    :rules="{
                      required: true,
                      message: '请输入批次号',
                      trigger: 'blur'
                    }"
                  >
                    <span style="margin-right: 12px">批次号</span>
                    <el-input
                      v-model="item.batchNum"
                      placeholder="批次号"
                      style="width: 70%"
                      clearable
                      maxlength="32"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    :prop="`partBatchList[${index}].produceDate`"
                    :rules="{
                      required: true,
                      message: '请选择生产日期',
                      trigger: 'change'
                    }"
                  >
                    <span style="margin-right: 12px">生产日期</span>
                    <el-date-picker
                      v-model="item.produceDate"
                      type="date"
                      placeholder="生产日期"
                      size="default"
                      style="width: 70%"
                      clearable
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item
                    :prop="`partBatchList[${index}].price`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入金额',
                        trigger: 'change'
                      }
                    ]"
                  >
                    <span style="margin-right: 12px">单价</span>
                    <el-input
                      v-model="item.price"
                      placeholder="单价"
                      style="width: 70%"
                      :disabled="item.id != ''"
                      @input="priceInput(item.price, index)"
                    />
                    <span>元</span>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item
                    :prop="`partBatchList[${index}].stockAmount`"
                    :rules="{
                      required: true,
                      message: '请输入库存数量',
                      trigger: 'blur'
                    }"
                  >
                    <span style="margin-right: 12px">库存数量</span>
                    <el-input
                      v-model="item.stockAmount"
                      placeholder="库存数量"
                      :disabled="item.id != ''"
                      class="input-with-select"
                      style="width: 80%"
                      @change="NumChange"
                      @input="stockAmountInput(item.stockAmount, index)"
                      type="number"
                    >
                      <template #append>
                        <el-select
                          v-model="ruleForm.partUnit"
                          placeholder="单位"
                          style="width: 120px"
                          :disabled="item.id != ''"
                        >
                          <el-option
                            v-for="item in partUnits"
                            :label="item.configValue"
                            :value="item.configValue"
                          />
                        </el-select>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <div
                    class="addList"
                    style="width: 50%"
                    @click="delBatchList(item)"
                    v-if="ruleForm.partBatchList.length > 1 && item.id == ''"
                  >
                    删除
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <div class="addList">
              <el-button type="primary" plain @click="addBatchList()">
                添加批次
              </el-button>
            </div>
          </el-form-item>
        </div>

        <div class="table">
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="实际库存" prop="realStock">
                <el-input
                  v-model="ruleForm.realStock"
                  type="number"
                  placeholder="请输入实际库存"
                  class="input-with-select"
                  clearable
                  :disabled="true"
                >
                  <template #append>
                    <el-select
                      v-model="ruleForm.partUnit"
                      placeholder="单位"
                      style="width: 120px"
                      :disabled="true"
                    >
                      <el-option
                        v-for="item in partUnits"
                        :label="item.configValue"
                        :value="item.configValue"
                      />
                    </el-select>
                  </template>
                </el-input>
                <span class="tips"
                  >实际库存将自动获取批次设置中的库存显示数量，多个批次数量累加计算</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最低安全库存" prop="safeStock">
                <el-input
                  v-model="ruleForm.safeStock"
                  type="number"
                  placeholder="请输入最低安全库存"
                  class="input-with-select"
                  clearable
                  min="0"
                  @input="safeInput"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="预警通知人" prop="noticeUser">
                <el-select
                  v-model="ruleForm.noticeUser"
                  class="m-2"
                  placeholder="请选择预警通知人"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in noticeUsers"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保质期" prop="qualityPeriod">
                <el-input
                  v-model="ruleForm.qualityPeriod"
                  placeholder="请输入保质期"
                  class="input-with-select"
                  clearable
                  maxlength="8"
                  show-word-limit
                  @input="qualityPeriodInput"
                >
                  <template #append>
                    <el-select
                      v-model="ruleForm.qualityUnit"
                      placeholder="单位"
                      style="width: 100px"
                    >
                      <el-option label="年" value="年" />
                      <el-option label="月" value="月" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row"> </el-row>
          <el-row class="row">
            <el-col :span="12">
              <el-form-item label="备件照片" prop="picture">
                <el-upload
                  class="avatar-uploader"
                  v-model:file-list="fileList"
                  list-type="picture-card"
                  :show-file-list="true"
                  :class="{ hide: hideUpload }"
                  v-loading="uploadLoading"
                  accept=".png,.jpg,jpeg"
                  :action="`${proxy.$http}/user/upload/uploadFile`"
                  :http-request="(resp: any) => { return handleUpload(resp, 14) }"
                  :headers="headers"
                  :data="{ type: '14' }"
                  :auto-upload="true"
                  :limit="1"
                  :on-error="(resp: any) => { return fileError(resp, 14) }"
                  :on-change="handleChange"
                  :before-upload="beforeImageUpload"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                >
                  <img
                    v-if="ruleForm.picture"
                    :src="ruleForm.picture"
                    class="avatar"
                  />
                  <el-icon v-else><Plus /></el-icon>
                </el-upload>
                <div class="tips" style="margin: auto auto 0 5px">
                  <span
                    style="
                      color: var(--el-color-primary);
                      cursor: pointer;
                      margin-right: 5px;
                    "
                    v-if="ruleForm.picture"
                    @click="delPictrue"
                    >删除</span
                  >
                  可传1张
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="row">
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input
                  v-model="ruleForm.remark"
                  :rows="4"
                  type="textarea"
                  placeholder="可输入备注信息"
                  clearable
                  maxlength="256"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确定
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog v-model="picVisible">
      <img
        style="width: 100%"
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
      />
    </el-dialog>
    <AddFileType
      :fileTypeDialog="fileTypeDialog"
      :typeString="typeString"
      @submitFileType="submitFileType"
    ></AddFileType>
  </div>
</template>
<script setup lang="ts">
import {
  ElLoading,
  ElMessage,
  FormInstance,
  FormRules,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadUserFile,
  genFileId
} from 'element-plus'
import {
  ref,
  reactive,
  onMounted,
  defineAsyncComponent,
  getCurrentInstance
} from 'vue'
import routes from '/@/router'
import {
  dictionaryList,
  getDirectorListApi,
  uploadFileApi
} from '/@/api/publicApi'
import { getSpareInfoApi, savePartApi, updatePartApi } from '/@/api/spare/index'
import { useRoute } from 'vue-router'
import { Session } from '/@/utils/storage'
import { Plus } from '@element-plus/icons-vue'
import {
  verifiyNumberInteger,
  verifyNumberIntegerAndFloat
} from '/@/utils/toolsValidate'
const AddFileType = defineAsyncComponent(
  () => import('../knowledge/components/AddFileType.vue')
)
const route = useRoute()
const id = ref(JSON.parse(JSON.stringify(route.query.id)))
onMounted(() => {
  getBJK()
  getSpareType('')
  getPartUnit()
  getDirectorList()
  if (id.value != '') {
    editDetail()
  }
})
const goBack = () => {
  routes.push({
    name: 'spareList'
  })
}
const { proxy } = getCurrentInstance() as any
const formSize = ref('default')
const storehouse = ref<any>([])
const partTypes = ref<any>([])
const noticeUsers = ref<any>([])
const partUnits = ref([
  {
    configValue: '',
    customizeFlag: '',
    id: '',
    parentId: ''
  }
])
const props = {
  expandTrigger: 'click' as const,
  value: 'id',
  label: 'configValue',
  emitPath: false
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  partName: '',
  partNum: '',
  storehouseId: '',
  storehouseName: '',
  partType: '',
  partTypeName: '',
  realStock: 0,
  partUnit: '',
  safeStock: '',
  noticeUser: '',
  qualityPeriod: '',
  qualityUnit: '年',
  picture: '',
  remark: '',
  partBatchList: [
    {
      id: '',
      batchNum: '',
      stockAmount: '',
      price: '',
      produceDate: ''
    }
  ]
})
const validateAvailableStock = (rule: any, value: any, callback: any) => {
  if (value <= ruleForm.value.realStock) {
    callback()
  } else {
    callback(new Error('不可大于实际库存'))
  }
}
const validateQualityPeriod = (rule: any, value: any, callback: any) => {
  if (ruleForm.value.qualityPeriod == '' || ruleForm.value.qualityUnit == '') {
    callback(new Error('请输入保质期时长'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  partName: [{ required: true, message: '请输入备件名称', trigger: 'blur' }],
  partNum: [{ required: true, message: '请输入备件编号', trigger: 'blur' }],
  storehouseId: [
    { required: true, message: '请选择所属备件库', trigger: 'change' }
  ],
  partType: [{ required: true, message: '请选择备件类型', trigger: 'change' }],
  realStock: [{ required: true, message: '请输入实际库存', trigger: 'change' }],
  safeStock: [
    { required: true, message: '请输入最低安全库存', trigger: 'blur' },
    { validator: validateAvailableStock, trigger: 'blur' }
  ],
  noticeUser: [
    { required: true, message: '请选择预警通知人', trigger: 'change' }
  ],
  qualityPeriod: [
    {
      required: true,
      validator: validateQualityPeriod,
      trigger: ['blur', 'change']
    }
  ]
})

const safeInput = (val: any) => {
  ruleForm.value.safeStock = verifiyNumberInteger(val)
}

const priceInput = (val: any, index: any) => {
  ruleForm.value.partBatchList[index].price = verifyNumberIntegerAndFloat(val)
}

const stockAmountInput = (val: any, index: any) => {
  ruleForm.value.partBatchList[index].stockAmount = verifiyNumberInteger(val)
}

const qualityPeriodInput = (val: any) => {
  ruleForm.value.qualityPeriod = verifiyNumberInteger(val)
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (id.value == '') {
        savePartApi(ruleForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '新增成功'
            })
            resetForm(formEl)
          }
        })
      } else {
        Reflect.set(ruleForm.value, 'id', id.value)
        updatePartApi(ruleForm.value).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: 'success',
              message: '修改成功'
            })
            routes.push({
              name: 'spareList'
            })
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  routes.push({
    name: 'spareList'
  })
}

const getBJK = () => {
  let params = { configType: 'part_library', keyword: '' }
  dictionaryList(params).then((res) => {
    if (res.code == 0) {
      storehouse.value = res.data
    }
  })
}
const getSpareType = (val: any) => {
  let params = { configType: 'part_type', keyword: '' }
  dictionaryList(params).then((res) => {
    if (res.code == 0) {
      partTypes.value = res.data
      if (val) {
        partTypes.value.forEach((e: any) => {
          if (e.configValue == val) {
            ruleForm.value.partType = e.id
            ruleForm.value.partTypeName = e.configValue
          }
        })
      }
    }
  })
}
const getPartUnit = () => {
  let params = { configType: 'part_unit', keyword: '' }
  dictionaryList(params).then((res) => {
    if (res.code == 0) {
      partUnits.value = res.data
      ruleForm.value.partUnit = res.data[0].configValue
    }
  })
}
const getDirectorList = () => {
  getDirectorListApi(5).then((res) => {
    if (res.code == 0) {
      noticeUsers.value = res.data
    }
  })
}
//图片上传
const uploadLoading = ref<boolean>(false) // 加载效果
const userInfo = Session.get('token')
const token = userInfo ? userInfo : ''
const headers = ref({
  'Content-Type': 'multipart/form-data',
  'Api-User-Token': token
})

const fileList = ref<UploadUserFile[]>([])
// 上传前，限制上传图片类型及大小
const beforeImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
  uploadLoading.value = true
  const testmsg = /^image\/(png|jpg|jpeg)$/.test(rawFile.type)
  if (!testmsg) {
    ElMessage.error('上传格式不正确,只支持png、jpg、jpeg!')
    uploadLoading.value = false
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    proxy.$message.error('图片大小不能超过10M!')
    uploadLoading.value = false
    return false
  }
}

const handleUpload = (file: any, type: any) => {
  uploadLoading.value = true
  uploadFileApi({ type: 14, file: file.file }).then((res) => {
    ruleForm.value.picture = res.data.fileIds[0]
    ElMessage.success('图片上传成功！')
    uploadLoading.value = false
  })
}

const fileError = (err: any, type: any) => {
  ElMessage.error('项目文件上传失败！')
  // fileList.value = []
}

// 图片上传后隐藏上传按钮
const hideUpload = ref<boolean>(false)
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  if (uploadFile) {
    hideUpload.value = true // 隐藏上传按钮
  }
}

// 删除上传的图片
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  ruleForm.value.picture = ''
  // 删除照片后显示上传按钮
  hideUpload.value = false
}

// 图片预览弹窗
const dialogImageUrl = ref('')
const picVisible = ref(false)
// 图片预览事件
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  picVisible.value = true
}

//添加批次
const addBatchList = () => {
  ruleForm.value.partBatchList.push({
    id: '',
    batchNum: '',
    stockAmount: '',
    price: '',
    produceDate: ''
  })
}
//删除批次
const delBatchList = (item: any) => {
  ruleForm.value.realStock = 0
  var index = ruleForm.value.partBatchList.indexOf(item)
  if (index !== -1) {
    ruleForm.value.partBatchList.splice(index, 1)
  }
  ruleForm.value.partBatchList.forEach((item: any) => {
    ruleForm.value.realStock += item.stockAmount * 1
  })
}
const storehouseChange = (val: any) => {
  ruleForm.value.storehouseName =
    proxy.$refs['storehouseRef'].getCheckedNodes()[0].label
}
const partTypeChange = (val: any) => {
  ruleForm.value.partTypeName =
    proxy.$refs['paetTypeRef'].getCheckedNodes()[0].label
}

const editDetail = () => {
  getSpareInfoApi(id.value).then((res) => {
    if (res.code == 0) {
      ruleForm.value.partName = res.data.partName
      ruleForm.value.partNum = res.data.partNum
      ruleForm.value.storehouseId = res.data.storehouseId
      ruleForm.value.storehouseName = res.data.storehouseName
      ruleForm.value.partType = res.data.partType
      ruleForm.value.partTypeName = res.data.partTypeName
      ruleForm.value.realStock = res.data.realStock
      ruleForm.value.safeStock = res.data.safeStock
      ruleForm.value.noticeUser = res.data.noticeUser
      ruleForm.value.qualityPeriod = res.data.qualityPeriod
      ruleForm.value.qualityUnit = res.data.qualityUnit
      ruleForm.value.partUnit = res.data.partUnit
      ruleForm.value.picture = res.data.picture
      ruleForm.value.remark = res.data.remark
      ruleForm.value.partBatchList = res.data.partBatchList
    }
  })
}

const NumChange = () => {
  ruleForm.value.realStock = 0
  ruleForm.value.partBatchList.forEach((item: any) => {
    ruleForm.value.realStock += item.stockAmount * 1
  })
}

const fileTypeDialog = ref(false)
const typeString = ref('part_type')
const addPartType = () => {
  fileTypeDialog.value = !fileTypeDialog.value
}

//添加类型回调
const submitFileType = (val: any) => {
  getSpareType(val)
  fileTypeDialog.value = !fileTypeDialog.value
}

const delPictrue = () => {
  ruleForm.value.picture = ''
  fileList.value = []
  // 删除照片后显示上传按钮
  hideUpload.value = false
}
</script>
<style scoped lang="scss">
.addSpare {
  .back {
    cursor: pointer;
    color: rgba(140, 140, 140, 1);
  }

  .table {
    width: 60%;
    padding: 20px 0px;

    .row {
      margin-bottom: 20px;
    }
  }
}

.tips {
  font-size: 13px;
  font-weight: 400;
  line-height: 21px;
  color: rgba(140, 140, 140, 1);
  text-align: left;
}

.addList {
  color: var(--el-color-primary);
  cursor: pointer;
}

.avatar-uploader .avatar {
  width: 84px;
  height: 84px;
  display: block;
}
</style>
<style>
.el-dialog__title {
  font-size: 20px !important;
  font-weight: 700 !important;
}

.avatar-uploader .el-upload {
  width: 84px;
  height: 84px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  text-align: center;
}
.hide .el-upload--picture-card {
  display: none;
}

.el-input__wrapper {
  background: white !important;
}

.el-upload-list__item {
  width: 84px !important;
  height: 84px !important;
}
</style>
